package com.example.mygrade.webapi;

import com.example.mygrade.core.PageUtils;
import com.example.mygrade.core.RUtil;
import com.example.mygrade.domain.SC;
import com.example.mygrade.domain.Student;
import com.example.mygrade.domain.Teacher;
import com.example.mygrade.intercepter.GlobalConstant;
import com.example.mygrade.service.SCService;
import com.example.mygrade.service.StudentService;
import com.example.mygrade.service.TeacherService;
import com.example.mygrade.vo.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;

@RestController
@RequestMapping("/webapi/teacher")
public class TeacherRestController {
    @Autowired
    private TeacherService teacherService;

    @Resource
    private SCService scService;

    @Autowired
    private StudentService studentService;

    /**
     * 读取得url:"/webapi/teacher/list"
     */
    @GetMapping("/list")
    public List<Teacher> getAll(){
        List<Teacher> teachers = teacherService.findAll();
        return teachers;
    }

    /**
     * 分页读取全部内容:"/webapi/teacher/getbypage"
     * @return
     */
    @GetMapping("/getbypage")
    public R getByPage(@RequestParam(value = "page",defaultValue="0") Integer page,
                               @RequestParam(value = "size",defaultValue = "10") Integer size,
                               @RequestParam(value = "tname",defaultValue = "") String tname,
                               @RequestParam(value = "sex",defaultValue = "") String sex,
                       @RequestParam(value = "sort",defaultValue = "id") String sortPassage,
                       @RequestParam(value = "direct",defaultValue = "ASC") String direct
    ){
        Page<Teacher> teacherPage;
        Sort sort;
        if (direct.equals("asc")){
            sort = Sort.by(Sort.Direction.ASC,sortPassage);
        }else{
            sort = Sort.by(Sort.Direction.DESC,sortPassage);
        }
        if(ObjectUtils.isEmpty(tname)  && ObjectUtils.isEmpty(sex)){
            Pageable pageable = PageRequest.of(page,size, sort);
            teacherPage = teacherService.findAll(pageable);
        }else if(ObjectUtils.isEmpty(tname) && !ObjectUtils.isEmpty(sex)){
            Teacher teacher = new Teacher();
            teacher.setSex(sex);
            Pageable pageable = PageRequest.of(page,size, sort);
            ExampleMatcher matcher = ExampleMatcher.matching()
                    //对性别的精确查询
                    .withMatcher("sex",ExampleMatcher.GenericPropertyMatchers.exact())
                    ;
            Example<Teacher> example = Example.of(teacher,matcher);
            teacherPage = teacherService.findAll(example,pageable);
        }else if(!ObjectUtils.isEmpty(tname) && ObjectUtils.isEmpty(sex)){
            Teacher teacher = new Teacher();
            teacher.setTname(tname);
            Pageable pageable = PageRequest.of(page,size, sort);
            ExampleMatcher matcher = ExampleMatcher.matching()
                    //对姓名的模糊查询
                    .withMatcher("tname",ExampleMatcher.GenericPropertyMatchers.contains())
                    ;
            Example<Teacher> example = Example.of(teacher,matcher);
            teacherPage = teacherService.findAll(example,pageable);
        }
        else{
            Teacher teacher = new Teacher();
            teacher.setTname(tname);
            teacher.setSex(sex);
            Pageable pageable = PageRequest.of(page,size, sort);
            ExampleMatcher matcher = ExampleMatcher.matching()
                    //对姓名的模糊查询
                    .withMatcher("tname",ExampleMatcher.GenericPropertyMatchers.contains())
                    //对性别的精确查询
                    .withMatcher("sex",ExampleMatcher.GenericPropertyMatchers.exact())
                    ;
            Example<Teacher> example = Example.of(teacher,matcher);
            teacherPage = teacherService.findAll(example,pageable);
        }

        PageUtils pageUtils = new PageUtils(teacherPage.getContent(),teacherPage.getTotalElements());
        return RUtil.success(pageUtils,"获取成功");
    }


    /**
     * 根据session获取老师所教学生成绩信息
     * @param page
     * @param size
     * @param httprequest
     * @return
     */
    @GetMapping("/getbystudent")
    public R getByStudent(@RequestParam(value = "page",defaultValue="0") Integer page,
                          @RequestParam(value = "size",defaultValue = "10") Integer size,
                          @RequestParam(value = "passage",defaultValue = "") String passage,
                          @RequestParam(value = "chooseValue",defaultValue = "") String chooseQuery,
                          @RequestParam(value = "sort",defaultValue = "id") String sortPassage,
                          @RequestParam(value = "direct",defaultValue = "ASC") String direct,
                          HttpServletRequest httprequest
    ){
        Page<SC> scPage;
        Sort sort;
        if (direct.equals("asc")){
            sort = Sort.by(Sort.Direction.ASC,sortPassage);
        }else{
            sort = Sort.by(Sort.Direction.DESC,sortPassage);
        }
        sort = Sort.by(Sort.Direction.ASC,sortPassage);

        HttpSession session = httprequest.getSession();
        Object obj = session.getAttribute(GlobalConstant.TEACHER_SESSION_KEY.getMsg());
        Teacher teacher = (Teacher) obj;
        String cname = teacher.getCname();

        if (ObjectUtils.isEmpty(passage)){
            SC sc = new SC();
            List<SC> sc1 = scService.findByCname(cname);
            sc.setCname(sc1.get(0).getCname());
            Pageable pageable = PageRequest.of(page,size, sort);
            ExampleMatcher matcher = ExampleMatcher.matching()
                    //对姓名的精确查询
                    .withMatcher("cname",ExampleMatcher.GenericPropertyMatchers.exact());
            Example<SC> example = Example.of(sc,matcher);
            scPage = scService.findAll(example,pageable);
        }else{
            switch (chooseQuery) {
                case "1": {
                    SC sc = new SC();
                    List<SC> sc1 = scService.findByCname(cname);
                    sc.setCname(sc1.get(0).getCname());
                    sc.setSname(sc1.get(0).getSname());
                    Pageable pageable = PageRequest.of(page,size, sort);
                    ExampleMatcher matcher = ExampleMatcher.matching()
                            //对姓名的精确查询
                            .withMatcher("cname",ExampleMatcher.GenericPropertyMatchers.exact())
                            .withMatcher("sname",ExampleMatcher.GenericPropertyMatchers.exact());
                    Example<SC> example = Example.of(sc,matcher);
                    scPage = scService.findAll(example,pageable);
                    break;
                }
                default: {
                    SC sc = new SC();
                    List<SC> sc1 = scService.findByCname(cname);
                    sc.setCname(sc1.get(0).getCname());
                    sc.setScore(Integer.parseInt(passage));
                    Pageable pageable = PageRequest.of(page,size, sort);
                    ExampleMatcher matcher = ExampleMatcher.matching()
                            //对姓名的精确查询
                            .withMatcher("score",ExampleMatcher.GenericPropertyMatchers.exact())
                            .withMatcher("cname",ExampleMatcher.GenericPropertyMatchers.exact());
                    Example<SC> example = Example.of(sc,matcher);
                    scPage = scService.findAll(example,pageable);
                    break;
                }
            }
        }


        PageUtils pageUtils = new PageUtils(scPage.getContent(),scPage.getTotalElements());
        return RUtil.success(pageUtils,"获取成功");
    }


    /**
     * 修改之前获取学生信息，读取的url:/webapi/teacher/get
     * @return
     */
    @GetMapping("/get/{id}")
    public R get(@PathVariable Integer id){
        Teacher teacher = teacherService.findById(id);
        teacher.setPassword("");
        return RUtil.success(teacher,"获取成功");
    }

    /**
     * 新增学生的方法/webapi/teacher/insert
     * @param teacher
     * @return
     */
    @PostMapping("/insert")
    public R insert(Teacher teacher){
        Teacher teacher1 = teacherService.insert(teacher);
        return RUtil.success(teacher1,"插入成功");
    }

    /**
     * 更新学生的方法/webapi/teacher/update
     * @param teacher
     * @return
     */
    @PutMapping("/update")
    public R update(Teacher teacher){
        Teacher oldteacher = teacherService.update(teacher);
        if (ObjectUtils.isEmpty(teacher.getPassword())){
            teacher.setPassword(oldteacher.getPassword());
        }
        Teacher teacher1 = teacherService.update(teacher);
        return RUtil.success(teacher1,"更新成功");
    }

    /**
     * 删除学生的方法/webapi/teacher/delete
     * @param id
     */
    @DeleteMapping("/delete/{id}")
    public R delete(@PathVariable Integer id){
        teacherService.delete(id);
        return RUtil.success(null,"删除成功");
    }

    /**
     * 批量删除学生
     * @param arr
     */
    @DeleteMapping("/batchdelete/{arr}")
    public R delete(@PathVariable Integer[] arr){

        teacherService.delete(arr);
        return RUtil.success(null,"批量删除成功");
    }

    /**
     * 批量导入教师
     */
    @RequestMapping("/importTeacher")
    @ResponseBody
    public R importTeacher(@RequestParam MultipartFile[] file, HttpSession session) throws Exception{
        int result = 0;
        try {
            result = teacherService.insertTeacher(file[0]);
        }catch (Exception e){
            e.printStackTrace();
        }

        if (result > 0){
            return RUtil.success(result,"导入成功");
//            return "{\"result\":\"excel文件数据导入成功！\"}";
        }else{
//            return "{\"result\":\"excel文件数据导入失败！\"}";
            return RUtil.error(400,"导入失败");
        }
    }

    /**
     * 修改教师密码
     * @param userName
     * @param oldpassword
     * @param newpassword
     * @return
     */
    @PostMapping("/updatepass")
    public R changePass(String userName,String oldpassword,String newpassword){
        Teacher teacher = teacherService.findByTnameLike(userName);
        if (teacher == null){
            return RUtil.error(500,"用户不存在！");
        }
        if (!oldpassword.equals(teacher.getPassword())){
            return RUtil.error(400,"旧密码错误");
        }
        teacher.setPassword(newpassword);
        Teacher teacher1 = teacherService.update(teacher);
        return RUtil.success(teacher1,"修改成功");
    }

    /**
     * 更改教师个人信息
     * @param tname
     * @param sex
     * @param tage
     * @param httprequest
     * @return
     */
    @PostMapping("/updateper")
    public R changeInfo(String tname,String sex,String tage,HttpServletRequest httprequest){
        HttpSession session = httprequest.getSession();
        Object obj = session.getAttribute(GlobalConstant.TEACHER_SESSION_KEY.getMsg());
        Teacher teacher = (Teacher) obj;
        teacher.setTname(tname);
        teacher.setSex(sex);
        teacher.setTage(Integer.parseInt(tage));

        Teacher teacher1 = teacherService.update(teacher);
        return RUtil.success(teacher1,"更改成功");
    }

    /**
     * 更改之前获取教师信息
     * @param httprequest
     * @return
     */
    @GetMapping("/queryinfo")
    public R queryInfo(HttpServletRequest httprequest){
        HttpSession session = httprequest.getSession();
        Object obj = session.getAttribute(GlobalConstant.TEACHER_SESSION_KEY.getMsg());
        Teacher teacher = (Teacher) obj;
        return RUtil.success(teacher,"获取成功");
    }
}
